import axios, {
  AxiosError,
  type AxiosInstance,
  type AxiosResponse,
  type InternalAxiosRequestConfig
} from 'axios'
import { type RequestConfig } from '@/models/request'
import message from './message'

// 实例化
const instance: AxiosInstance = axios.create({
  baseURL: '/api',
  timeout: 100000, // 超时时间：100s
  headers: {
    'content-type': 'application/json'
  }
})

// 请求拦截器
instance.interceptors.request.use(
  (config: InternalAxiosRequestConfig) => {
    return config
  },
  (error: AxiosError) => {
    message.error('请求失败')
    return Promise.reject(error)
  }
)

// 响应拦截器
instance.interceptors.response.use(
  (response: AxiosResponse) => {
    const responseDate = response.data
    if (responseDate.code == 0) {
      return responseDate
    }
  },
  (error: AxiosError) => {
    // console.log(error)
    return Promise.reject(error)
  }
)

// 封装请求
const request = async (config: RequestConfig) => {
  const { url, method, params, data } = config
  try {
    return await instance.request({
      url,
      method,
      params,
      data
    })
  } catch (error: any) {
    return handleRequestError(error)
  }
}

/**
 * 处理请求错误
 *
 * @param error 错误对象
 * @returns null
 */
const handleRequestError = (error: any) => {
  const data = error.response.data
  if (data) {
    message.error(data.message)
  } else {
    message.error('网络异常，请检查网络~')
  }
  return null
}

export default request
